package hikari.preferences.device_parameters;

import com.gooddies.texteditors.validation.AbstractValidator;
import hikari.persistence.file.FileSection;
import hikari.persistence.propertieseditor.editors.IPropertyEditor;
import java.io.IOException;
import javax.swing.JComboBox;
import javax.swing.JComponent;

/**
 * @author sad
 */
public class DevicePropertyEditor extends JComboBox<DriverType> implements IPropertyEditor {

    public DevicePropertyEditor() {
        for (DriverType driver : DriverType.getDriverTypes()) {
            addItem(driver);
        }
    }

    @Override
    public Object getEditorValue() {
        return (DriverType) getSelectedItem();
    }

    @Override
    public void setEditorValue(Object value) {
        DriverType driver = (DriverType) value;
        for (int i = 0; i < getItemCount(); i++) {
            if (getItemAt(i).equals(driver)) {
                setSelectedIndex(i);
                break;
            }
        }
    }

    @Override
    public void setMax(Object max) {
        throw new UnsupportedOperationException("DevicePropertyEditor does not support max property");
    }

    @Override
    public void setMin(Object min) {
        throw new UnsupportedOperationException("DevicePropertyEditor does not support min property");
    }

    @Override
    public void setValidator(AbstractValidator validator) {
        throw new UnsupportedOperationException("DevicePropertyEditor does not support validator property");
    }

    @Override
    public void setMaxLength(String length) {
        throw new UnsupportedOperationException("DevicePropertyEditor does not support length property");
    }

    @Override
    public JComponent getJComponent() {
        return this;
    }

    @Override
    public void save(String fieldName, FileSection section) throws IOException {
        section.writeLong(fieldName, ((DriverType) getSelectedItem()).getDriverType());
    }

    @Override
    public void read(String fieldName, FileSection section) throws IOException {
        long value = section.readLong(section.getChunk(fieldName));
        for (DriverType dt : DriverType.getDriverTypes()) {
            if (dt.getDriverType() == value) {
                setEditorValue(dt);
                return;
            }
        }
        throw new RuntimeException("Try to load field "+fieldName+" as DeviceProperty, but not found driver with number "+value);
    }
}
